<script setup>
import { inject, ref } from "vue";
import { useCounterStore } from "@/stores/upgrade";
import { handleGoBack } from "@/utils/router";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ordercheck, create, orderpay } from "@/services/pay.js";
import { replenishmentApi } from "@/services/cloudlibrary";
import { mine, isPayPassApi, checkPayPass } from "@/services/user";
import { selectReplenishmentStore } from "@/stores/selectReplenishment";
import { formatPrice } from "@/utils/formatPrice";

const selectReplenishmentData = selectReplenishmentStore();

import wxicon from "@/static/cloudlibrary/icon_weixin.png";
import yeicon from "@/static/cloudlibrary/icon_yue.png";
import dficon from "@/static/cloudlibrary/icon_daifu.png";

onLoad(() => {});

onShow(() => {
  isPayPassFun();
  if (selectReplenishmentData.selectReplenishment) {
    replenishmentData.value = selectReplenishmentData.selectReplenishment;
  }
  total_price.value = replenishmentData.value.total_price
    ? replenishmentData.value.total_price
    : 0;
  mineFun();
  ordercheckfun();
  // pay_type.value = balance.value < total_price.value ? 2 : 1;
});

const total_price = ref(0);

const paylist = ref([
  {
    title: "2",
    des: "微信支付（推荐）",
    icon: wxicon,
  },
  {
    title: "1",
    des: "余额支付 ",
    icon: yeicon,
  },
  // {
  //   title: "7",
  //   des: "他人代付",
  //   icon: dficon,
  // },
]);

const show = ref(false);
const replenishmentData = ref([]);
const pay_type = ref(1);
const form = ref({});

const showorder = ref(false);
const cartData = ref([]);
async function ordercheckfun() {
  replenishmentData.value.forEach((item, index) => {
    if (item.product_num > 0 && item.vip_price > 0) {
      cartData.value.push(item);
    }
  });

  const res = await ordercheck({
    cart: cartData.value,
    order_type: pay_type.value,
  });

  balance.value = res.data.user_balance.balance;
  ispayto.value = res.data.is_pay_order;
}

//计算商品总数
function numfun() {
  let num = 0;
  if (replenishmentData.value.length > 0) {
    replenishmentData.value.forEach((element, index) => {
      if (element.selectStatus) {
        num += element.product_num;
      }
    });
    return num;
  } else {
    return num;
  }
}

const balance = ref(0);
// 查询用户余额
const mineFun = async () => {
  try {
    // 发送请求
    let res = await mine();
    if (res.code == 200) {
      balance.value = res.data.balance;
      if (balance.value < total_price.value) {
        pay_type.value = 2;
      }
      // pay_type.value = balance.value < total_price.value ? 2 : 1;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const changenumfun = () => {
  ordercheckfun();
};

const cancle = () => {
  handleGoBack();
};

const order_id = ref(0);
const cerateFun = async () => {
  replenishmentData.value.forEach((item, index) => {
    if (item.product_num > 0) {
      cartData.value.push(item);
    }
  });
  form.value = {
    pay_type: pay_type.value,
    product: cartData.value,
  };
  try {
    let res = await replenishmentApi(form.value);
    order_id.value = res.data.order_id;
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

function onBridgeReady(yishen) {
  WeixinJSBridge.invoke("getBrandWCPayRequest", yishen, (res) => {
    // showgoPay.value = false;
    if (res) {
      uni.navigateTo({
        url:
          "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=0",
      });
      // 使用以上方式判断前端返回,微信团队郑重提示：
      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
    }
  });
}

const isPayPass = ref(0);
const isPayPassFun = async () => {
  try {
    let res = await isPayPassApi();
    if (res.code == 200) {
      isPayPass.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const isoldpay = ref(true);
const ispayto = ref(0);
const showPassword = ref(false);
const pay_pass = ref("");
const gopassword = () => {
  if (ispayto.value != 0 && isoldpay.value) {
    uni.showModal({
      title: "提示",
      content: "此商品已有未支付订单,是否继续支付购买",
      cancelText: "查看订单",
      confirmText: "确定下单",
      showCancel: true,
      success: ({ confirm, cancel }) => {
        if (confirm) {
          isoldpay.value = false;
          gopassword();
        }
        if (cancel) {
          uni.reLaunch({
            url: "/pages/order/orderlist/index?status=-2",
          });
        }
      },
    });

    return;
  }

  if (numfun() <= 0) {
    uni.showToast({
      title: "商品数量不能为0,请选择",
      icon: "none",
    });
    return;
  }

  if (pay_type.value == 1 && balance.value < total_price.value) {
    uni.showToast({
      title: "余额不足，无法支付",
      icon: "none",
    });
    return;
  }

  if (pay_type.value == 1 && isPayPass.value != 0) {
    showPassword.value = true;
    pay_pass.value = "";
    setTimeout(() => {
      focusinput.value = true;
    }, 500);
    return;
  } else if (pay_type.value == 1 && isPayPass.value == 0) {
    uni.showToast({
      title: "没有支付密码，前往设置",
      icon: "none",
    });

    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
      });
    }, 500);
    return;
  }
  if (pay_type.value == "2" || pay_type.value == "7") {
    gepaymentfun();
  }
};

const gocancle = () => {
  showPassword.value = false;
  pay_pass.value = "";
};
const ispay = ref(false);
const gepaymentfun = async () => {
  replenishmentData.value.forEach((item, index) => {
    if (item.product_num > 0 && item.vip_price > 0) {
      cartData.value.push(item);
    }
  });
  form.value = {
    pay_type: pay_type.value,
    product: cartData.value,
  };
  try {
    // 防止小程序输入密码重复支付
    if (!ispay.value) {
      ispay.value = true;
    } else {
      return;
    }
    let res = await replenishmentApi(form.value);
    order_id.value = res.data.order_id;
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    return;
  }
  ordercheckfun();

  let res = null;
  let yishen = null;
  try {
    if (pay_type.value == "1") {
      res = await orderpay({
        order_id: order_id.value,
        pay_type: 1,
        pay_pass: pay_pass.value,
      });
    }
    if (pay_type.value == "2") {
      try {
        // #ifdef H5
        res = await orderpay({ order_id: order_id.value, pay_type: 2 });
        yishen = JSON.parse(res.data.wxWcPayData);

        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener(
              "WeixinJSBridgeReady",
              onBridgeReady(yishen),
              false
            );
          } else if (document.attachEvent) {
            document.attachEvent("WeixinJSBridgeReady", onBridgeReady(yishen));
            document.attachEvent(
              "onWeixinJSBridgeReady",
              onBridgeReady(yishen)
            );
          }
        } else {
          onBridgeReady(yishen);
        }

        // #endif

        // #ifdef MP-WEIXIN
        res = await orderpay({ order_id: order_id.value, pay_type: 3 });
        // yishen = JSON.parse(res.data.wxWcPayData);
        yishen = res.data;
        if (res.code == 200) {
          // 仅作为示例，非真实参数信息。
          uni.requestPayment({
            provider: "wxpay",
            timeStamp: yishen.timeStamp,
            nonceStr: yishen.nonceStr,
            package: yishen.package,
            signType: yishen.signType,
            paySign: yishen.paySign,
            success: function (res) {
              // console.log("success:" + JSON.stringify(res));
              uni.redirectTo({
                url:
                  "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=200",
              });
            },
            fail: function (err) {
              uni.redirectTo({
                url:
                  "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=0",
              });
            },
          });
        } else {
          uni.redirectTo({
            url:
              "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=0",
          });
        }
        // #endif
      } catch (e) {
        uni.showToast({
          title: e.info,
          icon: "none",
        });
      }
    }
    if (pay_type.value == "7") {
      uni.navigateTo({
        url: "/pages/upgrade/payment/index?order_id=" + order_id.value,
      });
      return;
    }

    if (res.code == 200) {
      uni.showToast({
        title: "支付成功",
        icon: "none",
      });
      showPassword.value = false;
      selectReplenishmentData.setselectReplenishment([]);
      // uni.navigateTo({
      //   url:
      //     "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=" +
      //     res.code,
      // });
      uni.redirectTo({
        url:
          "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=" +
          res.code,
      });
    } else {
      uni.showToast({
        title: res.info,
        icon: "none",
      });
      // uni.navigateTo({
      //   url:
      //     "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=" +
      //     res.code,
      // });
      selectReplenishmentData.setselectReplenishment([]);
      uni.redirectTo({
        url:
          "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=" +
          res.code,
      });
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    selectReplenishmentData.setselectReplenishment([]);
    // uni.navigateTo({
    //   url:
    //     "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=" +
    //     e.code,
    // });
    uni.redirectTo({
      url:
        "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=" +
        e.code,
    });
  }
};

// const gepaymentfun = async () => {
//   try {
//     let res = await orderpay({
//       order_id: order_id.value,
//       pay_type: pay_type.value,
//     });
//     if (res.code == 200) {
//       if (pay_type.value == 1) {
//         uni.navigateTo({
//           url:
//             "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=" +
//             res.code,
//         });
//       } else if (pay_type.value == 2) {
//         let yishen = JSON.parse(res.data.wxWcPayData);

//         if (typeof WeixinJSBridge == "undefined") {
//           if (document.addEventListener) {
//             document.addEventListener(
//               "WeixinJSBridgeReady",
//               onBridgeReady(yishen),
//               false
//             );
//           } else if (document.attachEvent) {
//             document.attachEvent("WeixinJSBridgeReady", onBridgeReady(yishen));
//             document.attachEvent(
//               "onWeixinJSBridgeReady",
//               onBridgeReady(yishen)
//             );
//           }
//         } else {
//           onBridgeReady(yishen);
//         }

//         return;
//       } else if (pay_type.value == 7) {
//         uni.navigateTo({
//           url: "/pages/upgrade/payment/index?order_id=" + order_id.value,
//         });
//       }
//     } else {
//       uni.showToast({
//         title: res.info,
//         icon: "none",
//       });
//     }
//   } catch (e) {
//     uni.navigateTo({
//       url:
//         "/pages/cloudlibrary/replenishment_confirm/paystate/index?status=" +
//         e.code,
//     });
//     uni.showToast({
//       title: e.info,
//       icon: "none",
//     });
//   }
// };

const selecpayfun = (index) => {
  if (balance.value < total_price.value && index == 1) {
    uni.showToast({
      title: "余额不足",
      icon: "none",
    });
    return;
  }
  pay_type.value = index;
};

const closefun = () => {
  showPassword.value = false;
  focusinput.value = false;
};

// 定义 finish 方法
const finish = async (e) => {
  pay_pass.value = e;
  try {
    let res = await checkPayPass({ pay_pass: pay_pass.value });
    if (res.code == 200) {
      gepaymentfun();
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
  }
};
const forgot = () => {
  uni.navigateTo({
    url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
  });
};

const focusinput = ref(false);
</script>

<template>
  <view class="content">
    <view class="notice">
      <view class="notice-box">
        <image
          src="@/static/team/shopkeeper/notice.png"
          mode="widthFix"
        ></image>
        <view class="notice-text"
          >商品补货，仅支持采购到云仓库存，如需发货，请到首页下单</view
        >
      </view>
    </view>
    <view class="content-box">
      <view class="goods">
        <view class="goods-shore">
          <text>已选商品</text>
          <text>共{{ numfun() }}件</text>
        </view>
        <view
          class="goods-info"
          v-for="(item, index) in replenishmentData"
          :key="index"
        >
          <view class="goods-info-img">
            <image :src="item.image" mode="aspectFill" />
          </view>
          <view class="goods-info-detail">
            <view class="goods-info-detail-name">
              <view class="goods-name">{{ item.store_name }}</view>
            </view>
            <view class="goods-dec">默认</view>
            <view class="goods-priceornum">
              <view class="goods-price"
                ><text> ¥{{ formatPrice(item.vip_price) }}</text></view
              >
              <view class="goods-num">
                <up-number-box
                  integer
                  :min="0"
                  :max="100"
                  bgColor="#ffffff"
                  v-model="item.product_num"
                  @change="changenumfun"
                ></up-number-box>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="content-pay">
        <view
          class="content-pay-item"
          v-for="(item, index) in paylist"
          :key="index"
          @click="selecpayfun(item.title)"
        >
          <view
            :class="
              balance < total_price && item.title == 1
                ? 'content-pay-left noselect'
                : 'content-pay-left'
            "
          >
            <image :src="item.icon" mode="widthFix" />
            <text
              >{{ item.des
              }}{{
                item.title == 1 ? "(可用" + formatPrice(balance) + "元)" : ""
              }}</text
            >
          </view>
          <view class="content-pay-right" v-if="pay_type == item.title">
            <image src="@/static/cloudlibrary/select.png" mode="widthFix" />
          </view>
        </view>
      </view>
    </view>
  </view>

  <view class="content-footer">
    <view class="contebt-pays">
      <up-button class="pay-left" text="取消" @click="cancle"></up-button>
      <up-button
        @click="gopassword"
        class="pay-right"
        :text="pay_type == 7 ? '找人帮忙代付' : '立即支付'"
      ></up-button>
    </view>
  </view>

  <!-- 密码弹框 -->
  <u-popup
    :show="showPassword"
    mode="center"
    round="10"
    @close="closefun"
    @open="open"
  >
    <view class="password">
      <view class="popup-content-title">支付密码</view>
      <u-code-input
        v-model="pay_pass"
        :maxlength="6"
        dot
        size="80"
        @change="onChange"
        @finish="finish"
        :focus="focusinput"
      ></u-code-input>
      <view class="footer">
        <view class="closefun" @click="showPassword = false">取消</view>
        <view class="forgot" @click="forgot">忘记密码？</view>
      </view>
    </view>
  </u-popup>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
